import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Patch,
  Post,
} from '@nestjs/common';
import { DictSonService } from './dict-son.service';
import { CreateDictSonDto } from './dto/create-dict-son.dto';
import { UpdateDictSonDto } from './dto/update-dict-son.dto';
import { PageQuery } from '../../../util/entity/page.entity';
import { DictSon } from './entities/dict-son.entity';
import { DictService } from '../dict/dict.service';
import { HasRoles, HasPerms } from '../../../common/decorator/my.decorator';
import { Perm } from '../../../util/enum/perm.enum';
import { RoleEnum } from '../../../util/enum/role.enum';

@Controller()
export class DictSonController {
  constructor(
    private readonly dictSonService: DictSonService,
    private readonly dictService: DictService,
  ) {}

  /**
   * 子字典新增
   *  检查当前分类的code是否重复
   * @param dictId
   * @param createDictSonDto
   */

  @HasPerms(Perm.SysDictSonAdd)
  @Post(':dictId')
  async create(
    @Param('dictId') dictId: number,
    @Body() createDictSonDto: CreateDictSonDto,
  ) {
    await this.dictSonService.checkAddCodeUnique(createDictSonDto.code, dictId);
    createDictSonDto.dict = await this.dictService.findOne(dictId);
    return this.dictSonService.create(createDictSonDto);
  }

  /**
   * 子字典的分页查询
   * @param dictId
   * @param pageQuery
   */
  @Post('list/:dictId')
  getDictSonsByDictId(
    @Param('dictId') dictId: number,
    @Body() pageQuery: PageQuery<DictSon>,
  ) {
    return this.dictSonService.findListByDictId(dictId, pageQuery);
  }

  /**
   * 通过id查找
   * @param id
   */

  @HasPerms(Perm.SysDictSonEdit)
  @Get(':id')
  findOne(@Param('id') id: number) {
    return this.dictSonService.findOne(id);
  }

  /**
   * 修改子字典
   * @param id
   * @param updateDictSonDto
   */

  @HasPerms(Perm.SysDictSonEdit)
  @Patch(':id')
  async update(
    @Param('id') id: number,
    @Body() updateDictSonDto: UpdateDictSonDto,
  ) {
    const dictSon = await this.dictSonService.findOneWithDict(id);
    if (!dictSon) {
      throw new Error('没有父节点,程序错误');
    }
    await this.dictSonService.checkEditCodeUnique(
      updateDictSonDto.code,
      dictSon.dict.id,
      dictSon.code,
    );
    return this.dictSonService.update(id, updateDictSonDto);
  }

  @HasRoles(RoleEnum.Root)
  @HasPerms(Perm.SysDictSonDelete)
  @Delete(':id')
  remove(@Param('id') id: number) {
    return this.dictSonService.remove(id);
  }
}
